import sys
try:
    import gtk
except:
    sys.exit(1)

from gui import Gui
from config import Config
from scan import Scan
from utils.debug import *

class Channel(Gui):

    def __init__(self):
        '''
        Display channel list dialog
        '''
        Gui.__init__(self, 'channels', 'channels_dialog', {
            'on_cancel_button_released' : self.quit,
            'on_close_button_released' : self._close_button_released,
            'on_add_button_released' : self._add_button_released,
            'on_edit_button_released' : self._edit_button_released,
            'on_delete_button_released' : self._delete_button_released,
            'on_top_button_released' : self._top_button_released,
            'on_up_button_released' : self._up_button_released,
            'on_down_button_released' : self._down_button_released,
            'on_bottom_button_released' : self._bottom_button_released,
            'on_scanner_button_toggled' : self._scanner_button_toggled,
            'on_savetv_button_released' : self._savetv_button_released
        })
        
        self.connect(self.window, 'delete-event', self.quit)
        self.connect(self.window, 'response', self.quit)
        
        self.conf = Config()
        if not hasattr(self, 'populated'):
            self._populate()
        
        self.window.run()
    
    def quit(self, widget, *response):
        '''closing preferences-dialog'''
        if hasattr(self, 'scan') and self.scan.is_scanning:
            self.scan.stop()
        self.window.hide()        
        return True
    
    def _close_button_released(self, widget):
        '''close dialog and save config'''
        # FIXME: channel name cannot have any spaces
        self._save_channel_treeview(self.widget('channels_treeview'))
        self.quit(widget)
    
    def _add_button_released(self, widget):
        ''''''
        pass
    
    def _edit_button_released(self, widget):
        '''
        Pop-up channel_dialog for editing channel info
        get channels_treeview model, then get_iter, then model.get(column 0 to 1)
        then run() channelDialog
        if result is gtk.RESPONSE_OK (response id: -5), modify model.set()
        '''
        tselect = self.widget('channels_treeview').get_selection()
        model, t_iter = tselect.get_selected()
        if t_iter:
            from channeldialog import ChannelDialog
            c, f = model.get(t_iter, 1, 2)
            d = ChannelDialog(c, f)
            result, channel, frequency = d.run()
            if result == gtk.RESPONSE_OK: # modify treeview's ListStore to current changes
                model.set(t_iter, 1, channel)
                model.set(t_iter, 2, frequency)
    
    def _delete_button_released(self, widget):
        ''''''
        pass
    
    def _top_button_released(self, widget):
        '''move selected channel to top of the list'''
        self._move_channel('top')
    
    def _up_button_released(self, widget):
        '''move selected channel up'''
        self._move_channel('up')
    
    def _down_button_released(self, widget):
        '''move selected channel down'''
        self._move_channel('down')
    
    def _bottom_button_released(self, widget):
        '''move selected channel to bottom of the list'''
        self._move_channel('bottom')
    
    def _scanner_button_toggled(self, widget):
        '''toggle button to start tv scanning'''
        
        if widget.get_active():
            self.scan.start()
        else:
            self.scan.stop()
    
    def _savetv_button_released(self, widget):
        ''''''
        self._save_channel_treeview(self.widget('scanned_treeview'))
        self.channels['store'] = self.scanned['store']
        self.channels['tree'].set_model(self.channels['store'])
        widget.set_sensitive(False)
    
    def _populate(self):
        '''populate channels list into treeview'''
        c = gtk.CellRendererText()
        self.channels = {
            'tree' : self.widget('channels_treeview'),
            'store' : gtk.ListStore(int, str, str)
        }
        
        def cb_add_column(tree, text, cid):
            c = gtk.TreeViewColumn(text, gtk.CellRendererText(), text = cid)
            tree.append_column(c)
        
        cb_add_column(self.channels['tree'], '#', 0)
        cb_add_column(self.channels['tree'], 'Name', 1)
        cb_add_column(self.channels['tree'], 'Frequency', 2)
        
        for i in range(0, len(self.conf.get_conf('channels'))):
            c = self.conf.get_conf(['channels', str(i+1)])
            self.channels['store'].append([i+1, c[0], c[1]])
        self.channels['tree'].set_model(self.channels['store'])
        
        self.scanned = {
            'tree' : self.widget('scanned_treeview'),
            'store' : gtk.ListStore(int, str, str)
        }
        
        cb_add_column(self.scanned['tree'], '#', 0)
        cb_add_column(self.scanned['tree'], 'Name', 1)
        cb_add_column(self.scanned['tree'], 'Frequency', 2)
        self.scanned['tree'].set_model(self.scanned['store'])
        
        self.scan = Scan(self, self.scanned)
        self.populated = True
    
    def _move_channel(self, position):
        '''move selected channel to top/up/down/bottom of channel list'''
        tselect = self.widget('channels_treeview').get_selection()
        model, t_iter = tselect.get_selected()
        if t_iter:
            if position == 'top':
                model.move_after(t_iter, None)
            elif position == 'bottom':
                model.move_before(t_iter, None)
            elif position == 'up':
                path = (model.get_path(t_iter)[0]-1,)
                if path[0] == -1:
                    path = (0,)
                model.swap(t_iter, model.get_iter(path))
            elif position == 'down':
                p = model.get_path(t_iter)
                path = (p[0]+1,)
                try:
                    model.swap(t_iter, model.get_iter(path))
                except ValueError:
                    model.swap(t_iter, model.get_iter(p))
    
    def _save_channel_treeview(self, treeview):
        ''''''
        def save(model, path, t_iter, conf):
            c, f = model.get(t_iter, 1, 2)
            conf.set_conf(['channels', str(path[0]+1)], ['%s' % c, f])
        # reset current channel list
        self.conf.reset_conf('channels', 'dict')
        model = treeview.get_model()
        model.foreach(save, self.conf)
        self.conf.save()
